package com.pmpd.activity.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dmap.base.send.email.MailService;
import com.dmap.schedule.annotation.ElasticJobConf;
import com.pmpd.activity.constants.ActivityConstant;
import com.pmpd.activity.po.ActivityUser;
import com.pmpd.activity.service.api.ApiActivityProgressService;
import com.pmpd.activity.service.api.ApiActivityUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.List;

/**
 * @author guanming
 * @date 18-7-13下午2:52
 * @Description: 七天养成计划定时更新用户计步、睡眠和跑步数据;
 */
@ElasticJobConf(name="七天养成计划定时更新用户数据", cron="0 0 1 * * ?", eventTraceRdbDataSource="datasourcelog")
public class ActivityTimerSynchrodataJob implements SimpleJob {

    private final static Logger logger = LoggerFactory.getLogger(ActivityTimerSynchrodataJob.class);

    @Value("spring.profiles.active")
    private String environment;

    @Resource
    private ApiActivityProgressService apiActivityProgressService;
    @Resource
    private ApiActivityUserService apiActivityUserService;


    @Override
    public void execute(ShardingContext shardingContext) {
        try {
            //批量更新数据到progress表中
            apiActivityProgressService.bulkUpdate();

            //批量获取用户活动完成天数
            List<ActivityUser> users = apiActivityProgressService.getBulkProgress(ActivityConstant.SEVEN_DAYS_TRAINING_ID, ActivityConstant.STATE_PROGRESS_COMPLETE);

            //批量更新完成天数到user表中
            apiActivityUserService.bulkUpdate(users);

            try {
                MailService.sendMail(ActivityConstant.EMAIL_ADDRESS, ActivityConstant.EMAIL_SUBJECT + environment, "七天养成计划-更新某活动所有用户计步、睡眠和跑步数据成功");
            } catch (MessagingException me) {
                logger.error("七天养成计划-更新某活动所有用户计步、睡眠和跑步数据成功信息 MailService.sendMail error:  {}", me);
            }
        } catch (Exception e) {
            try {
                MailService.sendMail(ActivityConstant.EMAIL_ADDRESS, ActivityConstant.EMAIL_SUBJECT + environment, "七天养成计划-更新某活动所有用户计步、睡眠和跑步数据 error: " + e);
            } catch (MessagingException me) {
                logger.error("七天养成计划-更新某活动所有用户计步、睡眠和跑步数据error信息 MailService.sendMail error:  {}", me);
            }
        }
    }
}
